package route

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	adminRouters "seven-admin/app/admin/routers"
	adminService "seven-admin/app/admin/service"
	"seven-admin/app/middleware"
	"seven-admin/core"
	"seven-admin/core/config"
	"seven-admin/core/response"
	"strconv"
	"time"
)

func InitDI() {
	regFunctions := adminService.InitFunctions
	regFunctions = append(regFunctions, core.GetDB)
	for i := 0; i < len(regFunctions); i++ {
		if err := core.ProvideForDI(regFunctions[i]); err != nil {
			log.Fatalln(err)
		}
	}
}

func InitServer(router *gin.Engine) *http.Server {
	return &http.Server{
		Addr:           ":" + strconv.Itoa(config.Env.ServerPort),
		Handler:        router,
		ReadTimeout:    30 * time.Second,
		WriteTimeout:   30 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
}

func InitRouter() *gin.Engine {
	// 初始化gin
	gin.SetMode(config.Env.GinMode)
	router := gin.New()
	// 设置静态路径
	router.StaticFS(config.Env.StaticPath, http.Dir(config.Env.StaticDirectory))
	router.StaticFS("/public/uploads", http.Dir("public/uploads"))
	router.StaticFS("/public/export", http.Dir("public/export"))
	// 设置中间件
	router.Use(gin.Logger(), middleware.Cors(), middleware.ErrorRecover())
	// 演示模式
	if config.Env.DisallowModify {
		router.Use(middleware.ShowMode())
	}
	// 特殊异常处理
	router.NoMethod(response.NoMethod)
	router.NoRoute(response.NoRoute)
	// 注册路由
	group := router.Group("/api")
	//core.RegisterGroup(group, routers.CommonGroup, middleware.TokenAuth())
	//core.RegisterGroup(group, routers.MonitorGroup, middleware.TokenAuth())
	//core.RegisterGroup(group, routers.SettingGroup, middleware.TokenAuth())
	//core.RegisterGroup(group, routers.SystemGroup, middleware.TokenAuth())

	routers := adminRouters.InitRouters[:]
	for i := 0; i < len(routers); i++ {
		core.RegisterGroup(group, routers[i])
	}
	return router
}
